
var app = getApp()
var Bmob = require('../../utils/Bmob-2.2.0.min.js');
var WxParse = require('../../utils/wxParse/wxParse.js');
Page({
  data: {
    franchiseeId: '',
    franchiseeInfo: {},
    defaultPhoto: '',
    goodsList: [],
    appointmentList: [],
    tostoreList: [],
    has_goods_type: [],
    onBusiness: true,
    couponList: '',
showTab:true,
    open_status:1,
   cdnUrl: 'http://cdn.jisuapp.cn'
  },
  previewTpl: false, //是否是传模板id进来的预览
  onLoad: function(options){
    var franchiseeId = options.detail,
      that = this;
    //defaultPhoto = app.getDefaultPhoto();

    this.setData({
      franchiseeId: franchiseeId,
      //defaultPhoto: defaultPhoto
    })
    that.getFranchiseeInfo(franchiseeId);
    that.getGoodsList(franchiseeId);
    that.getCouponList(franchiseeId);
  },
  getFranchiseeInfo: function (id) {
    var that = this;
   
    var franchisee = Bmob.Query("Franchisee");
    console.log(id)

    franchisee.get(id).then(res=>{
   
      
        res.set('hot', res.hot + 1);
        res.save();
        
        that.setData({
          tabType:'info',
         
          franchiseeInfo: res

        })
        WxParse.wxParse('content', 'html', res.get("goods_content"), that);
    
    
    });


  },

  getGoodsList: function (objectId) {
    var that = this;
   
    var goods = Bmob.Query("goods");
    var franchisee= Bmob.Pointer("Franchisee");
    var franchiseeId = franchisee.set(objectId);
  
   
    goods.equalTo("FranchiseeId","==", franchiseeId);
    goods.equalTo("state","!=", 0);
    goods.find().then(res=>{
   
        //var goods=res;

        that.setData({

          goodsList: res

        })

     
    });



  },

  getCouponList: function (franchiseeId) {
    var that = this;
  
    var coupon = new Bmob.Query("coupon");

    var franchisee = Bmob.Pointer("Franchisee");
    var franchiseeId = franchisee.set(franchiseeId);
    coupon.equalTo("franchiseeID","==", franchiseeId);
    coupon.find().then(res=>{
            that.setData({

          couponList: res

        })

   
    });

  },

  getList: function (form) {
    var that = this;
    if (form == 'goods') {
      that.getGoodsList();
    } else if (form == 'appointment') {
      data.appointmentList = that.data.appointmentList.concat(goodsList.slice(0, 2));
    } else if (form == 'tostore') {
      that.gettostoreList();
    }

  },

  gettostoreList: function () {

    var that = this;
    var Tostore = Bmob.Object.extend("tostore");
    var goods = new Bmob.Query(Goods);

    var Franchisee = Bmob.Object.extend("Franchisee");
    var franchisee = new Franchisee();
    franchisee.id = objectId;
    goods.equalTo("FranchiseeId", franchisee);
    goods.find({
      success: function (res) {
        //var goods=res;

        that.setData({

          goodsList: res

        })

      },
      complete: function () {

      }
    });

  },
  turnToGoodsMore: function (e) {
    let form = e.currentTarget.dataset.form,
      typeData = e.currentTarget.dataset.type;
    app.turnToPage('/pages/goodsMore/goodsMore?detail=' + form + '&franchisee=' + this.data.franchiseeId + '&type=' + typeData);
  },
  turnToGoodsDetail: function (e) {
    let id = e.currentTarget.dataset.id;
    let form = e.currentTarget.dataset.type;
    if (form == 3) {
      app.turnToPage('/pages/toStoreDetail/toStoreDetail?detail=' + id + '&franchisee=' + this.data.franchiseeId);
    } else {
      app.turnToPage('/pages/goodsDetail/goodsDetail?detail=' + id + '&franchisee=' + this.data.franchiseeId + '&cart_num=' + this.data.franchiseeInfo.cart_goods_num);
    }
  },
  turnToCouponListDetail: function () {
    app.turnToPage('/pages/couponListPage/couponListPage?franchisee=' + this.data.franchiseeId);
  },
  franchiseeCoverOnload: function (e) {
    var originalWidth = e.detail.width,
      originalHeight = e.detail.height;

    //获取图片的原始长宽
    var windowWidth = 0;
    var imageWidth = 0, imageHeight = 0;

    var res = app.getSystemInfoData();

    windowWidth = res.windowWidth;
    imageWidth = windowWidth;
    imageHeight = imageWidth * originalHeight / originalWidth;
    this.setData({
      franchiseeCoverWidth: imageWidth,
      franchiseeCoverHeight: imageHeight > imageWidth ? imageWidth : imageHeight
    })
  },
  // 获取商家详情信息
  getAppShopByPage: function(){
    let that = this;
    let franchiseeId = this.data.franchiseeId;

    app.sendRequest({
      url: '/index.php?r=AppShop/GetAppShopByPage',
      data: {
        sub_shop_app_id: franchiseeId
      },
      success: function (res) {
        let newdata = {},
            data = res.data[0],
            has_goods_type = data.has_goods_type;

        data.business_time_str = data.business_time_str.replace(/\,/g, '\n');

        newdata['franchiseeInfo'] = data;
        !that.previewTpl && (newdata['TplId'] = +data.mode_id);

        if (data.mode_id == 2){
          that.getCategroyList();
        }else{
          if (has_goods_type.length) {
            for (let i = 0; i < has_goods_type.length; i++) {
              switch (+has_goods_type[i]) {
                case 0:
                  that.getGoodsList('goods');
                  break;
                case 1:
                  that.getGoodsList('appointment');
                  break;
                case 3:
                  that.getGoodsList('tostore');
                  break;
              }
            }
          }else{
            newdata['tabType'] = 'info';
            newdata['showTab'] = false;
          }
        }
        that.setData(newdata);
      }
    })
  },
  // 获取商品列表
 
  // 获取商城模板的商品
  getGoodsFromMode2: function (cate) {
    let that = this;
    let franchiseeId = that.data.requestFranchiseeId;

    app.sendRequest({
      url: '/index.php?r=AppShop/getGoodsList',
      data: {
        sub_shop_app_id: franchiseeId,
        form: 'goods',
        page: 1,
        'idx_arr[idx]': 'category',
        'idx_arr[idx_value]': cate
      },
      success: function (res) {
        var goodsList = res.data,
          newdata = {};
        newdata['goodsList'] = goodsList.slice(0, 4);

        that.setData(newdata);
      }
    })
  },
  // 获取商家二维码
  getFranchiseeQRCode: function () {
    let that = this;
    let franchiseeId = this.data.franchiseeId;

    app.sendRequest({
      url: '/index.php?r=AppShop/GenerateFranchiseeQRCode',
      data: {
        sub_app_id: franchiseeId,
        parent_app_id: app.getAppId(),
        p_u: app.globalData.p_u || ''
      },
      success: function (res) {
        let data = res.data;

        that.setData({
          'franchiseeInfo.sub_qr_code': data
        })
      }
    })
  },
  // 跳到更多商品
  

  // 跳转完善信息
  turnToFranchiseePerfect: function () {
    app.turnToPage('/franchisee/pages/franchiseePerfect/franchiseePerfect?franchisee_id=' + this.data.franchiseeId + '&shop_id=' + this.data.shopId);
  },

  // 跳转到当面付
  turnToTransferPage: function(){
    app.turnToPage('/eCommerce/pages/transferPage/transferPage?franchisee=' + this.data.franchiseeId);
  },
  // 跳转到vip详情
  turnToVipCard: function (e) {
    let id = e.currentTarget.dataset.id;
    app.turnToPage('/eCommerce/pages/vipCard/vipCard?detail=' + id + '&franchisee_id=' + this.data.requestFranchiseeId);
  },
  // 拨打电话
  makePhoneCall: function(e){
    var phone = e.currentTarget.dataset.phone;
    app.makePhoneCall(phone);
  },
  // 跳转小程序
  navigateToXcx: function(e){
    let app = e.currentTarget.dataset.app;
    app.navigateToXcx({
      appId: app
    })
  },
  // 地图
  franchiseeAddress: function(e){
    var dataset = e.currentTarget.dataset,
      eventParams = '';

    app.openLocation({
      latitude: +dataset.lat,
      longitude: +dataset.lng,
      scale: 20
    })
  },
  // 商品，评论，店铺信息tab切换
  tabChange: function(e){
    let type = e.currentTarget.dataset.type;

    this.setData({
      tabType: type
    });
  },
  // 显示模板列表
  showChangeTpl: function(){
    this.setData({
      franchiseeTplPop: true
    });
  },
  // 隐藏模板列表
  hiddenChangeTpl: function () {
    this.setData({
      franchiseeTplPop: false
    });
  },
  // // 修改模板
  // changeTpl: function(e){
  //   let id = e.currentTarget.dataset.id;
  //   let franchiseeId = this.data.franchiseeId;
  //   let shopId = this.data.shopId;
  //   let that = this;

  //   app.sendRequest({
  //     url: '/index.php?r=AppShop/UpdatModeByShopId',
  //     data: {
  //       parent_app_id: app.getAppId(),
  //       sub_app_id: franchiseeId,
  //       shop_id: shopId,
  //       mode_id: id
  //     },
  //     success: function (data) {
  //       app.globalData.franchiseeEnterStatusRefresh = true;
  //       let pages = getCurrentPages();
  //       for (let i = 0; i < pages.length; i++) {
  //         if (pages[i].page_router) {
  //           app.globalData['franchiseeTplChange-' + pages[i].page_router] = true;
  //         }
  //       }
  //       let tabBarPagePathArr = app.getTabPagePathArr();
  //       for (let i = 0; i < tabBarPagePathArr.length; i++) {
  //         let router = tabBarPagePathArr[i].split('/')[2];
  //         if (router) {
  //           app.globalData['franchiseeTplChange-' + router] = true;
  //         }
  //       }
  //       if (id == 1) {
  //         app.turnToPage('/franchisee/pages/franchiseeWaimai/franchiseeWaimai?detail=' + franchiseeId + '&shop_id=' + shopId, true);
  //       }else if(id == 3){
  //         app.turnToPage('/franchisee/pages/franchiseeTostore/franchiseeTostore?detail=' + franchiseeId + '&shop_id=' + shopId, true);
  //       }else {
  //         that.setData({
  //           franchiseeTplPop: false
  //         });
  //         that.getSubShopData();
  //       }
  //     }
  //   });
  // },
  // 修改模板
  changeTpl: function (e) {
    let id = e.currentTarget.dataset.id;
    let franchiseeId = this.data.franchiseeId;
    let shopId = this.data.shopId;
    let that = this;

    if (id == 1) {
      app.turnToPage('/franchisee/pages/franchiseeWaimai/franchiseeWaimai?detail=' + franchiseeId + '&shop_id=' + shopId, true);
    } else if (id == 3) {
      app.turnToPage('/franchisee/pages/franchiseeTostore/franchiseeTostore?detail=' + franchiseeId + '&shop_id=' + shopId, true);
    } else {
      that.previewTpl = true;
      that.setData({
        franchiseeTplPop: false,
        TplId: id
      });
      that.getSubShopData();
    }
  },
  // 确认修改模板
  changeTplConfirm: function (e) {
    let id = this.data.TplId;
    let franchiseeId = this.data.franchiseeId;
    let shopId = this.data.shopId;
    let that = this;

    app.sendRequest({
      url: '/index.php?r=AppShop/UpdatModeByShopId',
      data: {
        parent_app_id: app.getAppId(),
        sub_app_id: franchiseeId,
        shop_id: shopId,
        mode_id: id
      },
      success: function (data) {
        app.globalData.franchiseeEnterStatusRefresh = true;
        let pages = getCurrentPages();
        for (let i = 0; i < pages.length; i++) {
          if (pages[i].page_router) {
            app.globalData['franchiseeTplChange-' + pages[i].page_router] = true;
          }
        }
        let tabBarPagePathArr = app.getTabPagePathArr();
        for (let i = 0; i < tabBarPagePathArr.length; i++) {
          let router = tabBarPagePathArr[i].split('/')[2];
          if (router) {
            app.globalData['franchiseeTplChange-' + router] = true;
          }
        }
        app.turnToPage('/franchisee/pages/franchiseeEnterStatus/franchiseeEnterStatus?franchisee_id=' + franchiseeId );
      }
    });
  },
  // 获取预览数据
  getSubShopData: function(){
    var that = this;
    app.sendRequest({
      url: '/index.php?r=AppShop/GetSubShopData',
      data: {
        parent_app_id: app.getAppId(),
        app_id: that.data.franchiseeId,
        shop_id: that.data.shopId,
        p_u: app.globalData.p_u || ''
      },
      success: function (res) {
        let data = res.data[0];
        let newdata = {};

        newdata['franchiseeInfo'] = data;
        !that.previewTpl && (newdata['TplId'] = +data.mode_id);
        that.setData(newdata);

        if (data.mode_id == 2) {
          that.getCategroyList();
        } else {
          that.getGoodsList('goods');
          that.getGoodsList('appointment');
          that.getGoodsList('tostore');
        }
        that.getCoupons();
      }
    });
  },
  // 获取是否需要完善信息
  checkAppSubShopIsEdit: function () {
    var that = this;
    app.sendRequest({
      url: '/index.php?r=AppShop/CheckAppSubShopIsEdit',
      data: {
        parent_app_id: app.getAppId(),
        sub_app_id: that.data.franchiseeId,
        shop_id: that.data.shopId
      },
      success: function (res) {
        let is_edit = res.data.is_edit;
        that.setData({
          incompleteCrossband: is_edit == 0
        });
      }
    });
  },
  // 预览图片
  previewImage: function (e) {
    let that = this;
    let src = e.currentTarget.dataset.src;

    app.previewImage({
      current: src
    });
  },
  // 预览图片
  previewCarouselImage: function (e) {
    let that = this;
    let src = e.currentTarget.dataset.src;

    app.previewImage({
      current: src,
      urls: that.data.franchiseeInfo.carousel_imgs
    });
  },
  // 查看更多优惠券
  lookCouponMore: function () {
    this.setData({
      couponMore: !this.data.couponMore
    });
  },
  // 获取优惠券
  
  // 领取优惠券
  receiveCouponLoading: false,
  receiveCoupon: function (e) {
    let that = this;
    let coupon_id = e.currentTarget.dataset.id;
    let index = e.currentTarget.dataset.index;

    if (this.data.shopId) {
      app.showModal({
        content: '这是预览数据，无法领取!'
      });
      return;
    }
    if (this.receiveCouponLoading) {
      return;
    }
    this.receiveCouponLoading = true;
    app.sendRequest({
      url: '/index.php?r=AppShop/RecvCoupon',
      data: {
        'coupon_id': coupon_id,
        'sub_app_id': that.data.requestFranchiseeId
      },
      success: function (res) {
        app.showModal({
          content: '领取成功!'
        });
        if (res.data.is_already_recv == 1){
          let newdata = {};
          newdata['franchiseeInfo.coupon_list['+index+'].recv_status'] = 0;
          that.setData(newdata);
        }

      },
      complete: function () {
        that.receiveCouponLoading = false;
      }
    });
  },
  // 关闭立即完善
  closeIncomplete: function () {
    this.setData({
      incompleteCrossband: false
    });
  },
  // 商城模板的tab切换
  goodsModeTab: function(e){
    let cate = e.currentTarget.dataset.cate;

    this.getGoodsFromMode2(cate);
    this.setData({
      cateTab: cate ,
      goodsList: []
    })
  },
  // 获取会员卡数据
  getVIPCardList: function(){
    let that = this;
    app.sendRequest({
      url: '/index.php?r=AppShop/GetVIPCardList',
      data: {
        'parent_app_id': app.getAppId(),
        'sub_app_id': that.data.requestFranchiseeId
      },
      success: function (res) {
        that.setData({
          vipCardInfo: res.data.length ? res.data[0] : null
        });
      },
      complete: function () {
        
      }
    });
  },
  // 领取会员卡
  getVIPCardForUser: function () {
    let that = this;
    if (this.data.shopId) {
      app.showModal({
        content: '这是预览数据，无法领取!'
      });
      return;
    }
    app.sendRequest({
      url: '/index.php?r=AppShop/GetVIPCardForUser',
      data: {
        'parent_app_id': app.getAppId(),
        'sub_app_id': that.data.requestFranchiseeId
      },
      success: function (res) {
        app.showModal({
          content: '领取成功!'
        });
        that.setData({
          'vipCardInfo.is_owner': 1
        });
      },
      complete: function () {

      }
    });
  },
  // 获取轮播图
  getAppSubShopCarouselPhoto: function () {
    let that = this;
    app.sendRequest({
      url: '/index.php?r=AppShop/GetAppSubShopCarouselPhoto',
      data: {
        'sub_app_id': that.data.requestFranchiseeId
      },
      success: function (res) {
        let carousel = [];

        for (let i = 0; i < res.data.length; i++) {
          let c = res.data[i];
          if (c.form_data.isShow == 1) {
            carousel.push(c);
          }
        }

        that.setData({
          carousel: carousel
        });
      },
      complete: function () {

      }
    });
  },
  // 轮播点击事件
  carouselPhotoClick: function(e){
    let form = e.currentTarget.dataset.form;
    let action = form.action;
    let franchiseeId = this.data.franchiseeId;

    this.carouselEvent[action] && this.carouselEvent[action](form, franchiseeId);
  },
  // 轮播事件列表
  carouselEvent:{
    // 跳转页面
    'inner-link': function (form){
      let pageRoot = {
        'groupCenter': '/eCommerce/pages/groupCenter/groupCenter',
        'shoppingCart': '/eCommerce/pages/shoppingCart/shoppingCart',
        'myOrder': '/eCommerce/pages/myOrder/myOrder',
      };
      let pageLink = form['page-link'];
      let url = pageRoot[pageLink] ? pageRoot[pageLink] : '/pages/' + pageLink + '/' + pageLink;
      app.turnToPage(url);
    },
    // 跳转优惠券领取列表
    'coupon-receive-list': function (form){
      app.turnToPage('/eCommerce/pages/couponReceiveListPage/couponReceiveListPage');
    },
    // 当面付
    'transfer' : function(form){
      app.turnToPage('/eCommerce/pages/transferPage/transferPage');
    },
    // 拨打电话
    'call': function (form){
      app.makePhoneCall(form['phone-num']);
    },
    // 跳转小程序
    'turn-to-xcx': function (form){
      let app = form['xcx-appid'];
      app.navigateToXcx({
        appId: app
      })
    },
    // 商品买卖
    'goods-trade': function (form, franchiseeId) {
      let type = form['goods-type'];
      let id = form['goods-id'];
      if (type == 3) {
        app.turnToPage('/pages/toStoreDetail/toStoreDetail?detail=' + id + '&franchisee=' + franchiseeId);
      } else {
        app.turnToPage('/pages/goodsDetail/goodsDetail?detail=' + id + '&franchisee=' + franchiseeId );
      }
    }
  },
  showQRCodeComponent: function () {
    let that = this;
    
    if (that.data.shopId){
      app.showModal({
        content: '店铺未审核通过，不能分享'
      })
      return;
    }

    let animation = wx.createAnimation({
      timingFunction: "ease",
      duration: 400,
    });
    app.sendRequest({
      url: '/index.php?r=AppShop/ShareQRCode',
      data: {
        obj_id: that.data.franchiseeId,
        type: 2,
        text: that.data.franchiseeInfo.name,
        goods_img: that.data.franchiseeInfo.picture
      },
      success: function (res) {
        animation.bottom("0").step();
        that.setData({
          "pageQRCodeData.shareDialogShow": 0,
          "pageQRCodeData.shareMenuShow": true,
          "pageQRCodeData.imageUrl": res.data,
          "pageQRCodeData.animation": animation.export()
        })
      }
    })
  },
  // 分享
  onShareAppMessage: function () {
    let that = this;
    let title = that.data.franchiseeInfo.Franchisee_title;
    let desc = that.data.franchiseeInfo.description;
    let path = '/pages/franchiseeDetail/franchiseeDetail?detail=' + that.data.franchiseeId;
    return app.shareAppMessage({
      path: path,
      title: title,
      desc: desc,
      success: function () {
        
      }
    })
  }
})
